package cminus;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class AddFrame extends JFrame{
	private JPanel mainPane;	//该frame的JPane
	private JPanel namePane;	//项目名称
	private JLabel nameLabel;	//显示文件的JLabel
	private JTextField nameText;	//输入名称的JTextField
	private JPanel buttonPanel;	//放按钮的Panel
	private JButton confirmButton;	//确认按钮
	private JButton cancelButton;	//取消按钮
	
	public AddFrame( final AddInfo info)
	{
		mainPane = new JPanel();
		namePane = new JPanel();
		nameLabel = new JLabel(info.getInfo());
		nameText = new JTextField("",20);
		buttonPanel = new JPanel();
		confirmButton = new JButton("确定");
		cancelButton = new JButton("取消");
		
		//设置界面布局的代码
		mainPane.setLayout(new BoxLayout(mainPane,BoxLayout.Y_AXIS));
		addWindowListener(new WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				cancel(info);
			}
		});
		setLocation(200,200);
		//设置大小是否可变
		setResizable(false);
		
		//设置存放文本框的JPanel的布局
		namePane.setLayout(new BoxLayout(namePane,BoxLayout.X_AXIS));
		namePane.add(nameLabel);
		namePane.add(nameText);
		
		//给nameText添加监听器
		nameText.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent e) {
				//判断项目路径与名称是否有值, 如果两个text field都有值, 则确定按钮可用
				if (nameText.getText().equals("")) {
					confirmButton.setEnabled(false);
				} else {
					confirmButton.setEnabled(true);
				}
			}
		});
		//设置存放按钮的JPanel的布局
		buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.X_AXIS));
		//刚开始禁用按钮
		confirmButton.setEnabled(false);
		confirmButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				handerConfirm(info);
			}
		});
		//给取消按钮添加监听器
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				cancel(info);
			}
		});
		buttonPanel.add(confirmButton);
		buttonPanel.add(new JLabel(""));
		buttonPanel.add(cancelButton);
		
		//将文本框的JPanel和按钮的JPanel添加到mainPanel中
		mainPane.add(namePane);
		mainPane.add(buttonPanel);
		
		//将mainPanel添加到JFrame中
		add(mainPane);
		pack();
	}
	
	//处理确定按钮的点击
	private void handerConfirm(AddInfo info) {
		//获取得用户输入
		String data = nameText.getText();
		//新增后会涉及的一些与业务相关的操作留给Handler类处理
		info.getHandler().afterAdd(info.getEditorFrame(), this, data);
	}
	
	//取消添加时的处理
	private void cancel(AddInfo info) {
		//设置EditorFrame可用
		info.getEditorFrame().setEnabled(true);
		//让本窗口不可见
		setVisible(false);
	}
}
